package com.cd.javacxy.module.web.controller;

import com.cd.javacxy.common.model.entity.SessionUser;
import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import com.cd.javacxy.common.model.vo.SignInfoVo;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.exception.BussinessException;
import com.cd.javacxy.module.base.BaseController;
import com.cd.javacxy.module.web.service.CxySignInService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * CxySignIn的路由接口服务
 *
 * @author yanghy
 */
@Controller
@Slf4j
@RequestMapping("/sign")
public class CxySignInController extends BaseController {

    /**
     * CxySignInService服务
     */
    private CxySignInService cxySignInService;

    @Autowired
    public void setCxySignInService(CxySignInService cxySignInService) {
        this.cxySignInService = cxySignInService;
    }

    @ResponseBody
    @GetMapping("/info")
    public AjaxResponse<Object> loadSignInfo(HttpSession session) {
        Integer userId = this.getUserId(session);
        SignInfoVo signInfo = this.cxySignInService.findSignInfoByUserId(userId);
        return AjaxResponse.builder().code(ResponseCode.SUCCESS.getCode())
                .data(signInfo)
                .build();
    }

    @ResponseBody
    @PostMapping("/do")
    public AjaxResponse<Object> signIn(HttpSession session) {
        AjaxResponse<Object> ajaxResponse = AjaxResponse.builder().build();
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        try {
            this.cxySignInService.doSignIn(sessionUser);
            ajaxResponse.setCode(ResponseCode.SUCCESS.getCode());
        } catch (BussinessException e) {
            ajaxResponse.setErrorMsg(e.getLocalizedMessage());
            ajaxResponse.setCode(ResponseCode.BUSSINESSERROR.getCode());
            log.error("用户{}签到失败", sessionUser.getUserName());
        } catch (Exception e) {
            ajaxResponse.setErrorMsg(ResponseCode.SERVERERROR.getDesc());
            ajaxResponse.setCode(ResponseCode.SERVERERROR.getCode());
            log.error("用户签到失败,用户名={}", sessionUser.getUserName(), e);
        }
        return ajaxResponse;
    }


}
